#include <iostream>
#include "blockQueue.hpp"
#include "task.hpp"
#include <sys/types.h>
#include <unistd.h>
#include <ctime>
using namespace std;

template <class T, class V>
class BlockQueues
{
public:
    BlockQueue<T>* _queueClac;
    BlockQueue<V>* _queueSave;
};

void *productor(void *arg)
{
    BlockQueues<MathTask, SaveTask> *bms = static_cast<BlockQueues<MathTask, SaveTask> *>(arg);
    while (true)
    {
        int x = rand() % 10 + 1;
        int y = rand() % 10;
        int operCode = rand() % oper.size();        MathTask t(x, y, oper[operCode], mymath);
        bms->_queueClac->push(t);
        std::cout << "save thread,保存任务完成..." << std::endl;
    }
    return nullptr;
}

void *consumer(void *arg)
{
    BlockQueues<MathTask, SaveTask> *bms = static_cast<BlockQueues<MathTask, SaveTask> *>(arg);
    while (true)
    {
        MathTask t;
        bms->_queueClac->pop(&t);
        std::string result = t();
        std::cout << "cal thread,完成计算任务: " << result << " ... done" << std::endl;
        SaveTask s(result, save);
        bms->_queueSave->push(s);
    }
    return nullptr;
}

void *saver(void *arg)
{
    BlockQueues<MathTask, SaveTask> *bms = static_cast<BlockQueues<MathTask, SaveTask> *>(arg);
    while(true)
    {
        SaveTask s;
        bms->_queueSave->pop(&s);
        s();
        std::cout << "save thread,完成存储任务: " << " ... done" << std::endl;
    }
 

    return nullptr;
}

int main()
{

    // BlockQueue<MathTask>* bq =new BlockQueue<MathTask>();
    BlockQueues<MathTask, SaveTask> *bms = new BlockQueues<MathTask, SaveTask>();
    bms->_queueClac = new BlockQueue<MathTask>();
    bms->_queueSave = new BlockQueue<SaveTask>();
    // 随机数种子
    srand((unsigned long)time(nullptr) ^ getpid());

    // 创建两个消费者，3个生产者线程
    pthread_t b[2], p[3], s;
    pthread_create(p, nullptr, productor, bms);
    pthread_create(p + 1, nullptr, productor, bms);
    pthread_create(p + 2, nullptr, productor, bms);
    pthread_create(b, nullptr, consumer, bms);
    pthread_create(b + 1, nullptr, consumer, bms);
    pthread_create(&s, nullptr, saver, bms);

    // 回收资源
    pthread_join(b[0], nullptr);
    pthread_join(b[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    pthread_join(s, nullptr);

    delete bms->_queueClac;
    delete bms->_queueSave;
    delete bms;

    return 0;
}